package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;
	@Autowired
	private WxMaService wxMaService;
	@Autowired
	private RabbitService rabbitService;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private UserPaidAlbumMapper userPaidAlbumMapper;

	@Autowired
	private UserPaidTrackMapper userPaidTrackMapper;

	/**
	 * 微信登录
	 * @param code
	 * @return
	 */
	@Override
	public Map<String, Object> wxLogin(String code) {
		//创建map集合
		Map<String,Object> map=new HashMap<>();
		//获取openid
		WxMaJscode2SessionResult wxMaJscode2SessionResult = null;
		try {
			wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(code);
		} catch (WxErrorException e) {
			throw new RuntimeException(e);
		}
		String openid = wxMaJscode2SessionResult.getOpenid();
		//获取用户信息
		UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
		if (userInfo==null){//没有注册
			userInfo=new UserInfo();
			//赋值
			userInfo.setWxOpenId(openid);
			userInfo.setNickname("听友:"+System.currentTimeMillis());
			userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
			userInfoMapper.insert(userInfo);
			//发送消息
			rabbitService.sendMessage(MqConst.EXCHANGE_USER,MqConst.ROUTING_USER_REGISTER,userInfo.getId());
		}
		//创建token
		String token= UUID.randomUUID().toString().replaceAll("-","");
		String loginKey= RedisConstant.USER_LOGIN_KEY_PREFIX+token;
		//将用户信息存入redis中
		redisTemplate.opsForValue().set(loginKey,userInfo,RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
		map.put("token",token);
		return map;
	}

	/**
	 * 获取用户信息
	 * @param userId
	 * @return
	 */
	@Override
	public UserInfoVo getUserInfo(Long userId) {
		//创建对象
		UserInfoVo userInfoVo = new UserInfoVo();
		//查询用户信息
		UserInfo userInfo = getById(userId);
		//拷贝
		BeanUtils.copyProperties(userInfo,userInfoVo);
		return userInfoVo;
	}

	/**
	 * 更新用户信息
	 * @param userInfoVo
	 * @param userId
	 */
	@Override
	public void updateUser(UserInfoVo userInfoVo, Long userId) {
		//创建对象
		UserInfo userInfo = new UserInfo();
		//拷贝
		BeanUtils.copyProperties(userInfoVo,userInfo);
		userInfo.setId(userId);
		updateById(userInfo);
	}

	/**
	 * 判断用户是否购买过该专辑
	 * @param albumId
	 * @param trackIdList
	 * @param userId
	 * @return
	 */
	@Override
	public Map<Long, Integer> userIsPaidTrack(Long albumId, List<Long> trackIdList, Long userId) {
		//创建map集合
		Map<Long,Integer> map =new HashMap<>();
		//判断用户是否购买过该专辑
		UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getUserId, userId).eq(UserPaidAlbum::getAlbumId, albumId));
		if (null != userPaidAlbum){
			//购买了专辑
			return trackIdList.stream().collect(Collectors.toMap(trackId->trackId,trackId->1));
		}else {
			//判断是否购买声音
			//获取购买声音的id
			List<Long> userPaidTrackIdlist  = userPaidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getUserId, userId).in(UserPaidTrack::getTrackId, trackIdList)).stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
			for (Long trackId : trackIdList) {
				//判断userPaidTrackIdlist是否包含trackId
				if ((userPaidTrackIdlist.contains(trackId))){
					//包含 购买了
					map.put(trackId,1);
				}else {
					//未购买
					map.put(trackId,0);
				}
			}
		}
		return map;
	}

	/**
	 * 判断用户是否购买过该专辑
	 * @param albumId
	 * @param userId
	 * @return
	 */
	@Override
	public Boolean isPaidAlbum(Long albumId, Long userId) {
		return userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getAlbumId,albumId).eq(UserPaidAlbum::getUserId,userId))!=null;
	}
}
